package com.baizhi.service.impl;

import com.baizhi.entity.Category;
import com.baizhi.entity.Favorite;
import com.baizhi.entity.User;
import com.baizhi.entity.Video;
import com.baizhi.dao.VideoDao;
import com.baizhi.entity.VideoDetailVO;
import com.baizhi.entity.VideoVO;
import com.baizhi.feignclients.CategoryClients;
import com.baizhi.feignclients.UserClients;
import com.baizhi.service.VideoService;
import com.baizhi.utils.JSONUtils;
import com.baizhi.utils.RedisPrefix;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 视频(Video)表服务实现类
 *
 * @author makejava
 * @since 2024-02-18 21:04:55
 */
@Service("videoService")
public class VideoServiceImpl implements VideoService {

    private static final Logger log = LoggerFactory.getLogger(VideoServiceImpl.class);

    /**
     * 视频dao
     */
    @Resource
    private VideoDao videoDao;

    private UserClients userClients;

    private CategoryClients categoryClients;

    private StringRedisTemplate stringRedisTemplate;

    private RedisTemplate redisTemplate;

    private RabbitTemplate rabbitTemplate;

    @Autowired
    public VideoServiceImpl( UserClients userClients, CategoryClients categoryClients, StringRedisTemplate stringRedisTemplate, RedisTemplate redisTemplate, RabbitTemplate rabbitTemplate) {
        this.userClients = userClients;
        this.categoryClients = categoryClients;
        this.stringRedisTemplate = stringRedisTemplate;
        this.redisTemplate = redisTemplate;
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Video queryById(Integer id) {
        return this.videoDao.queryById(id);
    }

    @Override
    public List<VideoVO> queryAllByLimit(int offset, int limit) {
        offset = (offset - 1) * limit;
        //1.分页查询所有视频对象
        List<Video> videos = this.videoDao.queryAllByLimit(offset,limit);
        return getList(videos);
    }


    /**
     * 新增数据
     *
     * @param video 实例对象
     * @return 实例对象
     */
    @Override
    public Video insert(Video video) {
        this.videoDao.insert(video);
        return video;
    }

    /**
     * 修改数据
     *
     * @param video 实例对象
     * @return 实例对象
     */
    @Override
    public Video update(Video video) {
        this.videoDao.update(video);
        return this.queryById(video.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.videoDao.deleteById(id) > 0;
    }

    @Override
    public List<VideoVO> findAllByCategoryId(Integer page, Integer rows, Integer categoryId) {
        int start = (page - 1) * rows;
        List<Video> videos = videoDao.findAllByCategoryId(page, rows, categoryId);
        return getList(videos);
    }

    @Override
    public VideoDetailVO queryDetailById(String videoId, String token) {

        //1.根据 id 查询视频信息

        Video video = videoDao.queryById(Integer.valueOf(videoId));


        //2.创建 videoDetailVO
        VideoDetailVO videoDetailVO = new VideoDetailVO();

        //3.将 video 对象中基本信息 复制 到 videoDetailVO
        BeanUtils.copyProperties(video,videoDetailVO);

        //4.设置当前视频类别名称
        Category category = categoryClients.category(video.getCategoryId().toString());
        log.info("根据类别id查询到的类别信息为:{}",JSONUtils.writeValueAsString(category));
        videoDetailVO.setCategory(category.getName());

        //5.设置用户信息
        //调用用户服务
        User user = userClients.user(video.getUid().toString());
        log.info("根据id查询用户信息为:{}",JSONUtils.writeValueAsString(video));
        videoDetailVO.setUploader(user);

        //6.设置播放次数
        videoDetailVO.setPlaysCount(0);
        String playedCounts = stringRedisTemplate.opsForValue().get(RedisPrefix.VIDEO_PLAYED_COUNT_PREFIX + videoId);

        if(!StringUtils.isEmpty(playedCounts)){
            log.info("当前视频播放次数:{}",playedCounts);
            videoDetailVO.setPlaysCount(Integer.valueOf(playedCounts));
        }

        //7.设置点赞数
        videoDetailVO.setLikesCount(0);
        String likedCounts = stringRedisTemplate.opsForValue().get(RedisPrefix.VIDEO_LIKE_COUNT_PREFIX + video.getId());
        if(!StringUtils.isEmpty(likedCounts)){
            log.info("当前视频点赞数量为:{}",likedCounts);
            videoDetailVO.setLikesCount(Integer.valueOf(likedCounts));
        }

        //8.设置当前用户是否喜欢 不喜欢  收藏
        User o = (User) redisTemplate.opsForValue().get("session_" + token);
        if(!ObjectUtils.isEmpty(o)){
            //设置是否喜欢
            Boolean liked = stringRedisTemplate.opsForSet().isMember(RedisPrefix.USER_LIKE_PREFIX + o.getId(),videoId);
            videoDetailVO.setLiked(liked);
            //设置是否不喜欢
            Boolean disliked = stringRedisTemplate.opsForSet().isMember(RedisPrefix.USER_DISLIKE_PREFIX + o.getId(),videoId);
            videoDetailVO.setDisliked(disliked);
            //设置是否收藏
            Favorite favorite =  userClients.favorite(videoId,o.getId().toString());
            log.info("是否收藏过该视频: {}",ObjectUtils.isEmpty(favorite));
            if(!ObjectUtils.isEmpty(favorite)){
                videoDetailVO.setFavorite(true);
            }

        }

        return videoDetailVO;
    }

    /**
     * 将list video 转为 list videoVO
     * @param videos
     * @return
     */
    public List<VideoVO> getList(List<Video> videos){
        //创建VideoVo集合
        List<VideoVO> videoVOS = new ArrayList<>();
        //对video进行遍历 在遍历过程中转为videoVo
        videos.forEach(video -> {
//            VideoVO videoVO = get
        });
        return videoVOS;
    }

    /**
     * 将 video 转为 videoVO
     * @return
     */
    public VideoVO getVideoVO(Video video){
        //创建VideoVo
        VideoVO videoVO = new VideoVO();
        //复制属性
        BeanUtils.copyProperties(video,videoVO);

        //视频服务 -----> 调用用户服务 根据用户id查询用户
        User user = userClients.user(video.getUid().toString());
        log.info("根据id查询用户信息为:{}", JSONUtils.writeValueAsString(video));
        //设置用户名
        videoVO.setUploader(user.getName());

        //视频服务 ----> 调用类别服务   根据类别id 查询类别
        Category category = categoryClients.category(video.getCategoryId().toString());
        log.info("根据类别id查询到的类别信息为:{}",JSONUtils.writeValueAsString(category));
        videoVO.setCategory(category.getName());

        //设置点赞数量
        videoVO.setLikes(0);

        return videoVO;
    }
}
